import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/net/response/service_order_ddetail_data.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/viewmodel/service_order/service_order_detail_info_view_model.dart';
import 'package:ls_work/viewmodel/service_order/service_order_home_view_model.dart';
import 'package:ls_work/widgets/add_image_widget.dart';
import 'package:ls_work/widgets/requir_text_view.dart';
import 'package:ls_work/widgets/title_value_widget.dart';

import '../new_yyt_view_model.dart';

class ContinueServiceOrderViewModel extends BaseViewModel {
  ContinueServiceOrderViewModel(BuildContext context) : super(context);

  ServiceOrderDdetailData get detailData => ServiceOrderDetailInfoViewModel.detailData!;
  static const format = [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss];
  var serviceUpTime = DateTime.now().toDateStr(format);

  var info = "";

  var nextTime = "";

  List<String> files = [];

  Widget content() {
    return ListView(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      children: [
        TitleValueWidget(
          '服务挂起时间',
          text: serviceUpTime,
          showArrow: false,
        ),
        Gaps.dividerLine,
        TitleValueWidget(
          '责任部门',
          text: NewYytViewModel.userInfo?.officeName??"",
          showArrow: false,
        ),
        Gaps.dividerLine,
        TitleValueWidget(
          '责任人',
          text: NewYytViewModel.userInfo?.name??"",
          showArrow: false,
        ),
        Gaps.dividerLine,
        RequireTextView('服务挂起说明').addToContainer(
            width: double.infinity,
            padding: EdgeInsets.only(left: 16, top: 16, bottom: 10),
            color: Colors.white),
        CommonInput(
          hintText: '请输入描述信息',
          onChanged: (str) {
            info = str;
          },
          text: info,
          border: InputBorder.none,
          padding: EdgeInsets.zero,
          isDense: true,
          keyboardType: CommonInputType.multiline,
        ).addToContainer(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            color: Colors.white),
        Gaps.dividerLine,
        RequireTextView("上传照片").addToContainer(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            color: Colors.white,
            width: double.infinity),
        AddImageWidget(
          (files) {
            this.files = files;
          },
          files: this.files,
          cameramsg: "拍摄工单处理照片，需要申请您的相机权限",
          photomsg: "从相册选取工单处理照片，需要申请您的相册权限",
        ).addToContainer(color: Colors.white),
        Gaps.dividerLine,
        TitleValueWidget(
          '下次服务时间',
          hint: '请选择下次服务日期',
          isRequired: true,
          text: nextTime,
          showArrow: true,
        ).onTap(() {
          _selectNextTime();
        }),
        Gaps.dividerLine,
        ElevatedButton(
                onPressed: () {
                  hangUpService();
                },
                style: ButtonStyle(
                    shape: WidgetStateProperty.all(StadiumBorder()),
                    minimumSize:
                        WidgetStateProperty.all(Size(double.infinity, 40))),
                child: CommonText('服务挂起', textColor: Colors.white))
            .addToContainer(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                color: Colors.white)
      ],
    );
  }

  void _selectNextTime() {
    DatePicker.showDateTimePicker(context, onConfirm: (date) {
      nextTime = date?.toDateStr(format)??"";
      notifyListeners();
    });
  }

  void hangUpService(){
    if(info.isEmpty){
      showToast('请输入描述信息');
      return;
    }
    if(files.isEmpty){
      showToast('请选择照片');
      return;
    }
    if(nextTime.isEmpty){
      showToast('请选择下次服务时间');
      return;
    }
    continueService();
  }

  ///上传文件
  Future<List<Map<String, dynamic>>> _uploadFiles() async {
    List<Map<String, dynamic>> result = [];
    for (var file in files) {
      var data = await PostRequest.uploadFile(file);
      var bean = ResponseBean.fromJson(data);
      if ('0' == bean.code) {
        result.add(bean.data);
      } else {
        throw bean.msg ?? "";
      }
    }
    return result;
  }

  Future<void> continueService() async {
    showLoadingDialog();
    try {
      var uploadFiles = await _uploadFiles();
      var result = await PostRequest.nextService(
          detailData.id.toString(), info, nextTime, uploadFiles);
      var bean = ResponseBean.fromJson(result);
      if ("0" == bean.code) {
        showToast('提交完成');
        sendMessage(SendMessageEvent(MessageConfig.REFRESH_ORDER));
        finish();
      } else {
        showToast(bean.msg??"");
      }
      hideDialog();
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }


}
